<template>
  <div class="bar-wapper">
    <img src="@/assets/img/panel/titleArchiveType.png" width="460" alt="" />
    <div class="chart-box">
      <div ref="pieChart" style="width: 460px; height: 195px"></div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { ref, onUnmounted, watch } from 'vue';
import * as echarts from 'echarts';
type EChartsOption = echarts.EChartsOption;

const props = defineProps({
  data: {
    type: Object
  }
});
watch(
  () => props.data,
  (newVal) => {
    newVal && createPieChart();
  }
);

const pieChart = ref(null);
let chartInstance: any = null;

const createPieChart = () => {
  if (!pieChart.value) return;
  chartInstance = echarts.init(pieChart.value);
  const seriesData = props.data.map((item) => ({
    value: item.number,
    name: item.typeName,
    rate: item.rate
  }));
  const totalNumber = seriesData.reduce((total, item) => total + item.value, 0);
  const formatter = `{a|总数}\n{b|${totalNumber}}`;
  const option: EChartsOption = {
    tooltip: {
      trigger: 'item',
      position: 'right'
    },
    legend: {
      // 图例位置
      right: '5%',
      top: 'center', // 垂直居中
      orient: 'vertical', // 设置为垂直布局
      icon: 'circle',
      itemWidth: 8,
      itemHeight: 8,
      textStyle: {
        color: 'rgba(255, 255, 255, 0.65)', // 图例文字颜色
        fontSize: 12
      },
      // 自定义图例的formatter
      formatter: function (name) {
        const customData = seriesData.find((item) => item.name === name);
        if (customData) {
          return `${name} | ${customData.rate} ${customData.value}件`;
        }
        return name;
      }
    },
    series: [
      {
        type: 'pie',
        center: ['30%', '50%'], // 饼图的中心（圆心）坐标
        radius: ['70%', '90%'],
        label: {
          show: true,
          position: 'center',
          formatter,
          rich: {
            a: {
              fontSize: 14,
              color: 'rgba(255,255,255,0.45)',
              lineHeight: 30
            },
            b: {
              fontSize: 30,
              color: 'rgba(255,255,255,0.85)',
              lineHeight: 30
            }
          }
        },
        data: seriesData
      }
    ]
  };
  chartInstance.setOption(option);
};

onUnmounted(() => {
  if (chartInstance) {
    chartInstance.dispose();
  }
});
</script>
<style lang="less" scoped>
.bar-wapper {
  width: 460px;
  height: 312px;
  display: flex;
  flex-direction: column;
  .chart-box {
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    background: rgba(28, 53, 80, 0.49);
  }
}
</style>
